<?php

namespace App\Kuafu\Mqtt\Service;


use App\Kuafu\Mqtt\Enum\MqttCodeEnum;
use App\Kuafu\Mqtt\Model\Queue;
use App\Kuafu\Order\Service\OrderService;
use App\Kuafu\WaiMai\Enum\WaiMaiCacheEnum;
use App\Kuafu\WaiMai\Service\WaiMaiOrderService;
use App\Support\MQTT;
use App\Kuafu\Base\Service\BaseService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class MqttService extends BaseService
{
    /**
     * 支付成功 MQTT
     * @param $orderId
     * @param $sourceType
     */
    public function paySuccess($orderId, $sourceType, $deliveryType)
    {
        MQTT::send($this->shopId, MqttCodeEnum::MQTT_COMMAND_PAY_SUCCESS, [
            'orderId'      => (string)$orderId,
            'sourceType'   => $sourceType,
            'deliveryType' => (int)$deliveryType,
        ]);

    }

    /**
     * 更新菜单 MQTT
     */
    public function updateProductMenu()
    {
        MQTT::send($this->shopId, MqttCodeEnum::MQTT_COMMAND_UPDATE_PRODUCT_MENU, null);
    }

    /**
     * 更新支付方式列表
     */
    public function updatePayment()
    {
        MQTT::send($this->shopId, MqttCodeEnum::MQTT_COMMAND_UPDATE_PAYMENT, null);
    }

    /**
     * 外卖推送 MQTT
     * @param int $orderId 订单ID
     * @param int $sourceType 订单来源 美团/饿了么
     * @param int $operateType 消息类型 下单,骑手接单,骑手送达等状态
     * @param array $data 附加数据
     */
    public function takeOutOrder(int $orderId, int $sourceType, int $operateType, $data = [])
    {
        if (config('app.env') != 'prod' && config('waimai.testCallback')) {
            Log::debug("TEST CALLBACK 1");
            return;
        }

        $redisKey = WaiMaiCacheEnum::getMqttWaiMaiPush($orderId, $operateType, md5(json_encode($data)));
        if (Redis::exists($redisKey)) {
            Log::channel('waiMai')->info("MQTT-WAI-MAI-REPEATED: {$orderId}", [
                'sourceType'  => $sourceType,
                'operateType' => $operateType,
                'data'        => $data,
            ]);
            return;
        }
        Redis::set($redisKey, 1);
        Redis::expire($redisKey, 122);

        MQTT::send($this->shopId, MqttCodeEnum::MQTT_COMMAND_WAI_MAI_TAKE_OUT, [
            'orderId'     => (string)$orderId,
            'sourceType'  => $sourceType,
            'operateType' => $operateType,
            'data'        => $data ?: null,
        ]);
    }

    public function updateDeviceConfig()
    {
        // MQTT 推送设备更新配置
        MQTT::send($this->shopId, MqttCodeEnum::MQTT_COMMAND_UPDATE_DEVICE_CONFIG, [
            'timestamp' => time(),
        ], MQTT::MQTT_CLIENT_CONNECT_SHOP);
    }

    /**
     * 从队列中去数据
     *
     * @return mixed
     * @throws \App\Kuafu\WaiMai\Exceptions\WaiMaiException
     */
    public function popQueue()
    {
        $hasMore = false;
        $data    = Queue::pop($this->shopId);
        if ($data) {
            switch ($data['cmd']) {
                case MqttCodeEnum::MQTT_COMMAND_PAY_SUCCESS:
                    $data['order'] = OrderService::getOrderByIdAfterChange($this->shopId, $data['params']['orderId']);
                    break;
                case MqttCodeEnum::MQTT_COMMAND_WAI_MAI_TAKE_OUT:
                    $data['waiMaiOrder'] = WaiMaiOrderService::orderDetail($data['params']['orderId']);
                    break;
            }

            $hasMore = Queue::len($this->shopId) > 0;
        }

        return [
            'queue'   => $data ?: null,
            'hasMore' => $hasMore
        ];
    }

//    /**
//     * 更新自定义支付方式列表
//     */
//    public function updateCustomPayment()
//    {
//        MQTT::send($this->shopId, MqttCodeEnum::MQTT_COMMAND_UPDATE_CUSTOM_PAYMENT, null);
//    }

    /**
     * 通用Mqtt发送
     * @param $shopId
     * @param $command
     * @param $params
     */
    public function sendMqtt($shopId, $command, $params)
    {
        MQTT::send($shopId, $command, $params);
    }

}
